<template>
    <div class="common-page page-corp-company-add" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <comp-paths class="route" :paths="['/corp', '/corp/companys', $route.fullPath]"></comp-paths>
            <div class="title"></div>
        </div>
        <div class="common-page__body"></div>
        <comp-dialog title="添加企业/项目" ref="company" @close="addCompany('end')">
            <el-form size="small" label-width="140px" style="margin-right: 20px" @submit.native.prevent v-if="company">
                <!-- <el-form-item label="企业/项目LOGO：">
                    <img style="display: block; margin: 0 10px 10px 0; max-width: 120px; height: 60px; object-fit: cover" :src="company.logo.short" v-if="company.logo.id" />
                    <el-button type="plain" icon="el-icon-plus" @click="addCompany('upload-logo')">{{ company.logo.id ? "更换图片" : "选择图片" }}</el-button>
                </el-form-item> -->
                <el-form-item label="企业/项目类型：" required>
                    <el-select v-model="company.type" style="width: 480px" @change="addCompany('validate')">
                        <el-option v-for="data in env.companyTypes" :key="data.id" :label="data.name" :value="data.value">{{ data.name }}</el-option>
                    </el-select>
                </el-form-item>
                 <el-form-item label="社会信用统一代码：">
                    <el-input v-model="xydm" style="width: 480px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="企业/项目名称：" required>
                    <el-input ref="companyName" v-model="company.name" style="width: 480px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="企业/项目简介：">
                    <el-input type="textarea" v-model="company.desc" style="width: 480px" placeholder="请输入" :maxlength="1000" :rows="4" resize="none" :readonly="loading" @change="addCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="所在地址：" required>
                    <el-select v-model="company.city.id" style="margin-right: 10px; width: 230px" placeholder="城市" @change="addCompany('validate')">
                        <template v-for="data in citys">
                            <el-option :key="data.id" :label="data.name" :value="data.id" v-if="data.province.id === company.province.id"></el-option>
                        </template>
                    </el-select>
                    <el-select v-model="company.county.id" style="width: 240px" placeholder="县区" @change="addCompany('validate')">
                        <template v-for="data in countys">
                            <el-option :key="data.id" :label="data.name" :value="data.id" v-if="data.city.id === company.city.id"></el-option>
                        </template>
                    </el-select>
                    <div style="margin-top: 10px"></div>
                    <el-input v-model="company.location.address" style="width: 480px" placeholder="详细地址" :maxlength="100" :readonly="loading" @change="addCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="地址坐标：">
                    <el-input v-model="company.location.coord" style="width: 392px" placeholder="请输入" :readonly="loading" @change="addCompany('validate')"></el-input>
                    <el-tag style="margin-left: 10px" disable-transitions>
                        <span>坐标拾取</span>
                        <a style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" href="https://lbs.qq.com/tool/getpoint/index.html" target="_blank"></a>
                    </el-tag>
                </el-form-item>
                <el-form-item label="法定代表人：">
                    <el-input v-model="company.owner" style="width: 480px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="企业/项目规模：">
                    <el-select v-model="company.size" style="width: 480px" placeholder="请选择" @change="addCompany('validate')">
                        <el-option v-for="data in env.companySizes" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属行业：" required>
                    <!-- <el-input v-model="company.industry.name" style="width: 480px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addCompany('validate')"></el-input> -->
                     <el-select v-model="company.industry.name" style="width: 480px" placeholder="请选择" @change="addCompany('validate')">
                        <el-option key="0" label="第一产业（农、林、牧、渔业）" value="第一产业（农、林、牧、渔业）"></el-option>
                        <el-option key="1" label="工业" value="工业"></el-option>
                        <el-option key="2" label="建筑业" value="建筑业"></el-option>
                        <el-option key="3" label="第三产业（服务业）" value="第三产业（服务业）"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属分类：">
                    <el-select v-model="company.tag.id" style="width: 480px" placeholder="请选择" @change="addCompany('validate')">
                        <el-option v-for="data in tags" :key="data.id" :label="data.name" :value="data.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="服务小组：">
                    <el-select v-model="fwxz" style="width: 480px" placeholder="请选择" @change="addCompany('validate')">
                        <el-option key="17" label="市县自主调研" value="市县自主调研"></el-option>

                        <el-option key="0" label="第一组" value="第一组"></el-option>
                        <el-option key="1" label="第二组" value="第二组"></el-option>
                        <el-option key="2" label="第三组" value="第三组"></el-option>
                        <el-option key="3" label="第四组" value="第四组"></el-option>
                        <el-option key="4" label="第五组" value="第五组"></el-option>
                        <el-option key="5" label="第六组" value="第六组"></el-option>
                        <el-option key="6" label="第七组" value="第七组"></el-option>
                        <el-option key="7" label="第八组" value="第八组"></el-option>
                        <el-option key="8" label="第九组" value="第九组"></el-option>
                        <el-option key="9" label="第十组" value="第十组"></el-option>
                        <el-option key="10" label="第十一组" value="第十一组"></el-option>
                        <el-option key="11" label="第十二组" value="第十二组"></el-option>
                        <el-option key="12" label="第十三组" value="第十三组"></el-option>
                        <el-option key="13" label="第十四组" value="第十四组"></el-option>
                        <el-option key="14" label="第十五组" value="第十五组"></el-option>
                        <el-option key="15" label="第十六组" value="第十六组"></el-option>
                        <el-option key="16" label="第十七组" value="第十七组"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="联系人：">
                    <el-tag style="margin-right: 10px; max-width: 351px" disable-transitions v-if="company.employees.length > 0">{{ company.employees.map((employee) => employee.client.name).join("、") }}</el-tag>
                    <el-button type="plain" icon="el-icon-plus" @click="addCompany('pick-employees-start')">编辑联系人</el-button>
                </el-form-item>
                <el-form-item label="服务专员：" required>
                    <el-tag style="margin-right: 10px; max-width: 351px" disable-transitions v-if="company.helpers.length > 0">{{ company.helpers.map((helper) => helper.user_name).join("、") }}</el-tag>
                    <el-button type="plain" icon="el-icon-plus" @click="addCompany('pick-helpers-start')">选择服务专员</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="addCompany('submit')">添加</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addCompany('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="编辑联系人" ref="companyEmployees">
            <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="company">
                <el-form-item v-for="(employee, index) in employees" :key="index" :label="'联系人' + (index + 1) + '：'">
                    <el-input v-model="employee.client.name" style="margin-right: 10px; width: 120px" placeholder="姓名" :maxlength="100" :readonly="loading" @change="addCompany('pick-employees-validate')"></el-input>
                    <el-input v-model="employee.client.mobile" style="margin-right: 10px; width: 160px" placeholder="手机号" :maxlength="100" :readonly="loading" @change="addCompany('pick-employees-validate')"></el-input>
                    <el-input v-model="employee.duty" style="margin-right: 10px; width: 160px" placeholder="担任职务" :maxlength="100" :readonly="loading" @change="addCompany('pick-employees-validate')"></el-input>
                    <el-button type="plain" icon="el-icon-delete" @click="addCompany('pick-employees-delete', employee)"></el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="addCompany('pick-employees-submit')">完成</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addCompany('pick-employees-end')">取消</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="选择服务专员" ref="companyHelpers">
            <el-form size="small" label-width="84px" style="margin-right: 20px;" @submit.native.prevent v-if="company">
                <el-form-item label-width="1" style="margin-bottom: 80px">
                    <div style="min-width: 320px; max-width: 520px;height:500px">


                    <el-input class="filter" v-model="keyword" size="small" style="width: 320px" clearable placeholder="请输入" :readonly="loading" @keyup.enter="handleQuery">
                        <span slot="prepend">联络员名称</span>
                    </el-input>
                        <el-button class="filter" type="primary" size="small" @click="handleQuery()">查询</el-button>

                    <el-table re size="medium" height="100%" :data="deepts" @header-click="onTableHeaderClick" @row-click="onTableRowClick" @selection-change="onTableSelectionChange">
                        <el-table-column type="selection" align="center"></el-table-column>


                        <el-table-column prop="user_name" label="联络员/账号" width="auto" min-width="120" />
                        <el-table-column prop="user_role" label="角色" width="auto" min-width="120" />


                    </el-table>
                    <div style="">
                       
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page.sync="pageNum"
                            :page-sizes="[100, 200, 300, 400]"
                            :page-size="pageSize"
                            layout="sizes, prev, pager, next"
                            :total="total">
                        </el-pagination>

                    </div>

                    </div>
                </el-form-item>
                <el-form-item label-width="1">
                    <el-button type="primary" icon="el-icon-check" @click="addCompany('pick-helpers-submit')">完成</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addCompany('pick-helpers-end')">取消</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, float, deepCopy, selectFile } from "../util";
    export default {
        name: "page-corp-company-add",
        title: "添加企业/项目",
        nodes: ["/menu/corp"],
        childs: [],
        mixins: [mixin],
        data: () => ({
            loading: false,
            company: null,
            keyword:null,
            self: false,
            citys: [],
            countys: [],
            tags: [],
            employees: [],
            helpers: [],
            depts: [],
            deepts:[],
            openId:false,
            xydm:null,
            fwxz:null,
            selected:[],
            pageSize:100,
            pageNum:1,
            total:0
        }),
        methods: {
            handleQuery(){
                this.plugins.user.getOrderDeptDepmentskeyWord(this.keyword).then(res =>{
                            if (res.code === 0) this.deepts = res.data;this.total = res.total
                            });
            },
            handleSizeChange(val){
                this.pageSize = val
                this.getlianList(this.pageSize,this.pageNum)
            },
            handleCurrentChange(val){
                this.pageNum =val
                this.getlianList(this.pageSize,this.pageNum)
            },
            onTableHeaderClick() {
                // this.select && this.$refs.table.toggleAllSelection();
            },
            onTableRowClick(row) {
                // this.select && this.$refs.table.toggleRowSelection(row);
            },
            onTableLinageChange(value) {
                // this.filters.linage = value;
                // this.search(true);
            },
            onTablePageChange(value) {
                // this.filters.page = value;
                // this.search(true);
            },
            onTableSelectionChange(selects) {
                console.log(selects);
                this.selected = selects
                // this.filters.ids = selects.map((data) => data.id);
                // this.selects = selects;
            },
            getlianList(a,b){
                     this.plugins.user.getOrderDeptDepmentsObjectss(a,b).then(res =>{
                            if (res.code === 0) this.deepts = res.data;this.total = res.total
                            });
            },
            addCompany(action, data) {
                if (this.loading) return;
                let company = this.company;
                
                let citys = this.citys;
                let countys = this.countys;
                let tags = this.tags;
                let depts = this.depts;
                let profile = this.profile;
                if (!action || action === "start") {
                    this.loading = true;
                    this.plugins.user.call(async () => {
                        if (tags.length > 0) return { code: 0 };
                        let res = await this.plugins.user.getCompanyOfTags();
                        if (res.code === 0) this.tags = res.data;
                        return res;
                    }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.company = this.plugins.user.formatCompany();
                            this.company.type = "company";
                            this.company.province.id = "450000";
                            this.company.status = "approving";
                            this.addCompany("validate");
                            this.$refs.company.init();
                            this.$nextTick(() => this.$refs.companyName.focus());
                        } else {
                            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "validate") {
                    let error = "";
                    company.name = string(company.name).trim();
                    // company.fwxz = string(this.fwxz).trim();
                    company.xydm = string(this.xydm).trim();
                    error = error || (company.name ? "" : "请输入企业/项目名称！");
                    company.desc = string(company.desc);
                    company.city.id = string(() => citys.find((city) => city.id === company.city.id && city.province.id === company.province.id).id);
                    company.county.id = string(() => countys.find((county) => county.id === company.county.id && county.city.id === company.city.id).id);
                    error = error || (company.province.id && company.city.id && company.county.id ? "" : "请完善所在地址！");
                    company.location.address = string(company.location.address).trim();
                    // error = error || (company.location.address ? "" : "请填写详细地址");
                    error = error || (company.industry.name ? "" : "所属行业必填！");

                    company.location.coord = string(company.location.coord).trim();
                    company.location.lng = Math.min(Math.max(float(company.location.coord.split(",")[1], 6), 0), 180);
                    company.location.lat = Math.min(Math.max(float(company.location.coord.split(",")[0], 6), 0), 90);
                    company.location.coord = company.location.lng > 0 && company.location.lat > 0 ? company.location.lat + "," + company.location.lng : "";
                    company.owner = string(company.owner).trim();
                    error = error || (company.helpers.length > 0 ? "" : "请选择服务专员！");
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "upload-logo") {
                    if (!data) return selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else this.addCompany(action, file);
                    });
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    this.loading = true;
                    this.plugins.user.uploadFile(data, "image", progress).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            company.logo = res.data;
                            this.addCompany("validate");
                        } else {
                            this.plugins.modal.alert("图片上传失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "pick-employees-start") {
                    let employees = deepCopy(company.employees);
                    while (employees.length < 5) employees.push(this.plugins.user.formatEmployee());
                    this.employees = employees;
                    this.$refs.companyEmployees.init();
                } else if (action === "pick-employees-validate") {
                    let employees = this.employees;
                    let error = "";
                    for (let employee of employees) {
                        let index = employees.indexOf(employee);
                        let name = employee.client.name = string(employee.client.name).trim();
                        let mobile = employee.client.mobile = string(employee.client.mobile).trim();
                        let duty = employee.duty = string(employee.duty).trim();
                        if (name || mobile || duty) {
                            error = error || (name ? "" : "请输入联系人" + (index + 1) + "的姓名！");
                            error = error || (mobile ? "" : "请输入联系人" + (index + 1) + "的手机号！");
                            error = error || (/^1[3-9]\d{9}$/.test(mobile) ? "" : "联系人" + (index + 1) + "的手机号格式不正确！");
                            error = error || (duty ? "" : "请输入联系人" + (index + 1) + "的担任职务！");
                        }
                    }
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "pick-employees-delete") {
                    let employee = data;
                    employee.client.id = "";
                    employee.client.name = "";
                    employee.client.mobile = "";
                    employee.duty = "";
                } else if (action === "pick-employees-submit") {
                    if (!this.addCompany("pick-employees-validate", true)) return;
                    company.employees = this.employees.filter((employee) => employee.client.name || employee.client.mobile || employee.duty);
                    this.addCompany("pick-employees-end");
                    this.addCompany("validate");
                } else if (action === "pick-employees-end") {
                    this.$refs.companyEmployees.close();
                } 
                else if (action === "pick-helpers-start") {
                    this.$nextTick(()=>{
                        this.deepts.forEach(row=>{
                        this.selected.forEach(selected =>{
                            if(selected.user_id === row.user_id){
                                console.log(this.$refs.table);
                                
                            }
                        })
                        })
                    })
                    this.loading = true;
                    this.plugins.user.call(async () => {
                        // if (depts.length > 0) return;
                        // for (let depment of profile.depments) {
                            
                            // let dept = depment.dept;
                            this.getlianList(this.pageSize,this.pageNum)
                           
                           
                        // }
                    }, async () => {
                        for (let dept of depts) {
                            for (let depment of dept.depments) {
                                console.log(depment.selected);
                                depment.dept.id = dept.id;
                                depment.dept.name = dept.name;
                                depment.selected = company.helpers.some((helper) => helper.client.id === depment.client.id);
                            }
                        }
                    }).then(() => {
                        this.loading = false;
                        this.$refs.companyHelpers.init();
                    });
                } else if (action === "pick-helpers-submit") {
                    company.depts = [];
                    company.helpers = this.selected;
                    console.log(company.helpers);

                    console.log(this.selected);
                    // this.onTableSelectionChange()


                    // depts.forEach((dept) => dept.depments.forEach((depment) => {
                    //     if (!depment.selected) return;
                    //     if (!company.depts.some((dept) => dept.id === depment.dept.id)) {
                    //         let dept = this.plugins.user.formatDept();
                    //         dept.id = depment.dept.id;
                    //         dept.name = depment.dept.name;
                    //         company.depts.push(dept);
                    //     }
                    //     if (!company.helpers.some((helper) => helper.client.id === depment.client.id)) {
                    //         let helper = this.plugins.user.formatHelper();
                    //         helper.client.id = depment.client.id;
                    //         helper.client.name = depment.client.name;
                    //         company.helpers.push(helper);
                    //     }
                    // }));
                    this.addCompany("pick-helpers-end");
                    this.addCompany("validate");
                } else if (action === "pick-helpers-end") {
                    this.$refs.companyHelpers.close();
                } else if (action === "submit") {
                    if (!this.addCompany("validate", true)) return;
                    this.loading = true;
                    company.helpers = this.selected;
                    console.log(this.selected);
                    this.plugins.user.addCompany(company).then((res) => {
                        this.loading = false;
                        console.log(company);
                        if (res.code === 0) {
                            this.plugins.modal.toast("添加成功！", "success");
                            this.addCompany("end");
                        } else {
                            this.plugins.modal.alert("添加失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.company.close();
                    this.$router.back();
                }
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                this.loading = true;
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.citys = this.plugins.user.citys;
                        this.countys = this.plugins.user.countys;
                        this.self = this.profile.role === "holder";
                        this.self ? this.addCompany() : this.$router.replace("/corp/companys");
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/corp/companys"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-corp-company-add {
        overflow: hidden;
    }
</style>